<?php
namespace backend\components;

use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\helpers\Html;
use yii\widgets\Menu as BaseMenu;

/**
 * Class Menu
 * @package app\components\widgets
 * Theme menu widget.
 */
class Menu extends BaseMenu
{
    /**
     * @inheritdoc
     */
    public $linkTemplate = '<a href="{url}"><i class="{icon}"></i><span> {label} </span>{down}</a>';
    public $submenuTemplate = "<ul class='treeview-menu'>{items}</ul>";
    public $firstItemCssClass = 'treeview';
    public $lastItemCssClass = '';
    public $activateParents = true;

    protected function normalizeItems($items, &$active)
    {
        $user = Yii::$app->getUser();
       
        foreach ($items as $i => $item) {
            if (isset($item['visible']) && !$item['visible']) {
                unset($items[$i]);
                continue;
            }
            if (!isset($item['label'])) {
                $item['label'] = '';
            }
            $encodeLabel = isset($item['encode']) ? $item['encode'] : $this->encodeLabels;
            $items[$i]['label'] = $encodeLabel ? Html::encode($item['label']) : $item['label'];
            $hasActiveChild = false;
            if (isset($item['url']))
            {
                if(!$this->canDo($user, $item['url']))
                {
                    unset($items[$i]);
                    continue;
                }
            }
            if (isset($item['items'])) {
                $items[$i]['items'] = $this->normalizeItems($item['items'], $hasActiveChild);
                if (empty($items[$i]['items']) && $this->hideEmptyItems) {
                    unset($items[$i]['items']);
                    if (!isset($item['url'])) {
                        unset($items[$i]);
                        continue;
                    }
                }
            }
            if (!isset($item['active'])) {
                if ($this->activateParents && $hasActiveChild || $this->activateItems && $this->isItemActive($item)) {
                    $active = $items[$i]['active'] = true;
                } else {
                    $items[$i]['active'] = false;
                }
            } elseif ($item['active']) {
                $active = true;
            }
        }

        return array_values($items);
    }

    protected function renderItems($items, $level = 1)
    {
        $n = count($items);
        $lines = [];
        foreach ($items as $i => $item) {
            $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', []));
            $tag = ArrayHelper::remove($options, 'tag', 'li');
            
            $class = [];
            if ($item['active']) {
                $class[] = $this->activeCssClass;
            }
            if ($i === 0 && $this->firstItemCssClass !== null) {
                $class[] = $this->firstItemCssClass;
            }
            if ($i === $n - 1 && $this->lastItemCssClass !== null) {
                $class[] = $this->lastItemCssClass;
            }
            if (!empty($class)) {
                if (empty($options['class'])) {
                    $options['class'] = implode(' ', $class);
                } else {
                    $options['class'] .= ' ' . implode(' ', $class);
                }
            }

            $menu = $this->renderItem($item);
            $submenuTemplate=$this->submenuTemplate;
            if (!empty($item['items'])) {
                $menu .= strtr($submenuTemplate, [
                    '{items}' => $this->renderItems($item['items'], $level+1),
                ]);
            }

            $lines[] = Html::tag($tag, $menu, $options);
        }

        return implode("\n", $lines);
    }

    protected function renderItem($item)
    {
        if(0&&isset($item['items']))
            $linkTemplate = '<a href="{url}"><span class="ared">{label}</span></a>';
        else
            $linkTemplate = $this->linkTemplate;
        $template = ArrayHelper::getValue($item, 'template', $linkTemplate);
        $replace = [
            '{url}' => Url::to(isset($item['url']) ? $item['url'] : '#'),
            '{label}' => $item['label'],
            '{icon}'=>$item['icon'],
            '{down}'=>isset($item['items'])?'<i class="fa fa-angle-right pull-right"></i>':'',
            '{ismenu}'=>isset($item['items'])?'class="dropdown-toggle"':'',
        ];
        return strtr($template, $replace);
    }

    protected function canDo($user, $url)
    {
        return true;
        $auth = Yii::$app->getAuthManager();
        $permissions = $auth->getPermissionsByUser($user->id);
      // print_r($url);
        if(is_array($url))
            $url=$url[0];
       $url=explode('?',$url);
        return isset($permissions[$url[0]]);
    }
     /**
     * Checks whether a menu item is active.
     * This is done by checking if [[route]] and [[params]] match that specified in the `url` option of the menu item.
     * When the `url` option of a menu item is specified in terms of an array, its first element is treated
     * as the route for the item and the rest of the elements are the associated parameters.
     * Only when its route and parameters match [[route]] and [[params]], respectively, will a menu item
     * be considered active.
     * @param array $item the menu item to be checked
     * @return boolean whether the menu item is active
     */
    protected function isItemActive($item)
    {
        
        /*
        if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) {
            $route = Yii::getAlias($item['url'][0]);
            $route=explode('?',$route);
            $route=isset($route[0])?$route[0]:$route;
            if ($route[0] !== '/' && Yii::$app->controller) {
                $route = Yii::$app->controller->module->getUniqueId() . '/' . $route;
            }
            if (ltrim($route, '/') !== $this->route) {
                return false;
            }
            unset($item['url']['#']);
           
            if (count($item['url']) > 1) {
                $params = $item['url'];
                unset($params[0]);
                foreach ($params as $name => $value) {
                    if ($value !== null && (!isset($this->params[$name]) || $this->params[$name] != $value)) {
                        return false;
                    }
                }
            }

            return true;
        }
        */
        if (isset($item['url']) ) {
            $cRoute= \Yii::$app->request->getPathInfo();
            if($cRoute==$item['url'])
            {
                return true;
            }
            //print_r($this->route);
            //echo Yii::getAlias($item['url']);
            //return true;

        }
        return false;
    }
}